﻿using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class MusicText : MonoBehaviour, IPointerEnterHandler,IPointerExitHandler
{
    public float time = 30;
    ScrollRect scrollRect;
    RectTransform rectTransform;
    Text text;
    bool isMove = true;
    bool isPause = false;
    // Start is called before the first frame update
    void Awake()
    {
        scrollRect = this.GetComponentInParent<ScrollRect>();
        rectTransform = this.GetComponent<RectTransform>();
        text = this.GetComponent<Text>();        
    }

    public void SetText(string content)
    {
        text.text = content;
        rectTransform.sizeDelta = new Vector2(GetStrWidth(content,text.fontSize), rectTransform.sizeDelta.y);        
    }

    public void SetMusic(MusicData musicData)
    {
        SetText(musicData.ToString());
        if (GameData.musicSpeed != 0)
            this.time = musicData.time / GameData.musicSpeed;
        else
            isMove = false;
    }

    private void Update()
    {
        if(isMove)
        {
            if (isPause == false)
            {
                if (scrollRect.horizontalNormalizedPosition <= 1)
                {
                    scrollRect.horizontalNormalizedPosition += 1 / time * Time.deltaTime;
                }
            }            
        }        
    }

    //获取长度方法
    private int GetStrLength(string str)
    {
        if (string.IsNullOrEmpty(str)) return 0;
        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        byte[] s = ascii.GetBytes(str);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }
        }
        return tempLen;
    }

    private float GetStrWidth(string str,float size)
    {
        if (string.IsNullOrEmpty(str)) return 0;
        ASCIIEncoding ascii = new ASCIIEncoding();
        float tempLen = 0;
        byte[] s = ascii.GetBytes(str);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += size;
            }
            else
            {
                tempLen += size / 80 * 46;
            }
        }
        return tempLen;
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        isPause = true;
        print("进入");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        isPause = false;
        print("离开");
    }
}
